package com.cyy.admin.service;

import com.cyy.admin.entity.SysMenuEntity;
import com.cyy.admin.repository.SysMenuRepository;
import com.cyy.common.MenuItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * author Chenyuyi
 * date 2021/12/10  10:32
 */
@Service
public class SysMenuService {

    @Autowired
    private SysMenuRepository repository;

    public Collection<MenuItem> loadMenusByRoleId(String roleId) {
        /*
         * 首先，加载顶级目录或页面菜单
         */
        List<SysMenuEntity> menus = repository.findAllByRoleId(roleId);
        //创建菜单集合
        LinkedHashMap<String, MenuItem> root = new LinkedHashMap<String, MenuItem>();
        //循环添加菜单到菜单集合
        for (SysMenuEntity menu : menus) {
            MenuItem item = new MenuItem(menu.getName(), null);
            item.setId(menu.getId());
            item.setPid(menu.getPid());
            item.setMenuType(menu);
            item.setUrl(StringUtils.trimToEmpty(menu.getUrl()));
            if(item.isRootMenu()) {
                root.put(item.getId(), item);
            }
        }
        for (SysMenuEntity menu : menus) {
            MenuItem item = new MenuItem(menu.getName(), null);
            item.setId(menu.getId());
            item.setPid(menu.getPid());
            item.setMenuType(menu);
            item.setUrl(StringUtils.trimToEmpty(menu.getUrl()));
            if(!item.isRootMenu() && !item.isButton()) {
                MenuItem parentItem = root.get(item.getPid());
                if(parentItem != null) {
                    parentItem.addClild(item);
                } else {
                    System.out.println("菜单项"+item.getName()+"("+item.getId()+")没有对应的父级菜单");
                }
            }
        }
        return root.values();
    }
}
